#!/usr/bin/env node

/**
 * 工作流状态查看脚本
 * 显示当前执行进度和产物状态
 */

const fs = require('fs');
const path = require('path');

const componentName = process.argv[2];

if (!componentName) {
  console.error('❌ 请提供组件名称');
  console.error('用法: npm run workflow:status ComponentName');
  process.exit(1);
}

const progressFile = `./${componentName}/.workflow/progress.json`;

if (!fs.existsSync(progressFile)) {
  console.error(`❌ 找不到进度文件: ${progressFile}`);
  console.error('提示: 请先运行 npm run workflow:start', componentName);
  process.exit(1);
}

const progress = JSON.parse(fs.readFileSync(progressFile, 'utf8'));

// 状态图标映射
const statusIcons = {
  not_started: '⭕',
  in_progress: '🔄',
  completed: '✅',
  failed: '❌',
  skipped: '⏭️',
  recovered: '♻️'
};

// 显示头部信息
console.log(`
╔════════════════════════════════════════════════╗
║           工作流执行状态                       ║
╚════════════════════════════════════════════════╝
`);

console.log(`📦 组件: ${progress.workflow.component}`);
console.log(`📊 状态: ${progress.workflow.status}`);
console.log(`⏰ 开始时间: ${progress.workflow.startTime}`);
console.log(`🔄 最后更新: ${progress.workflow.lastUpdate}`);

if (typeof progress.currentPhase === 'number') {
  console.log(`🧭 当前Phase: Phase${progress.currentPhase}`);
  console.log(`🛠️ 当前任务: ${progress.currentTask || '未设置'}`);
}

if (progress.nextAction) {
  console.log(`➡️ 下一动作: ${progress.nextAction}`);
}

if (Array.isArray(progress.nextChecklist) && progress.nextChecklist.length) {
  console.log('\n✅ 恢复清单:');
  progress.nextChecklist.forEach((item, idx) => {
    console.log(`   ${idx + 1}. ${item}`);
  });
}

if (Array.isArray(progress.requiredDocs) && progress.requiredDocs.length) {
  console.log('\n📚 必读文档状态:');
  progress.requiredDocs.forEach((doc) => {
    const status = doc.status === 'read' ? '✅ 已读' : '📝 待读';
    console.log(`   ${status} ${doc.path}`);
  });
}

if (Array.isArray(progress.promptGuidance) && progress.promptGuidance.length) {
  console.log('\n🧠 提示词指引:');
  progress.promptGuidance.forEach((prompt) => {
    const status = prompt.status === 'used' ? '✅ 已用' : '✨ 建议';
    console.log(`   ${status} ${prompt.template} - ${prompt.purpose}`);
  });
}

console.log('');

// 显示Phase进度
console.log('📋 Phase执行进度:\n');

const phaseNames = {
  phase0: '参数处理和方案解析',
  phase1: 'Figma数据提取',
  phase2: 'Preview组件生成',
  phase3: '配置设计',
  phase4: '配置面板渲染',
  phase5: '系统集成验证'
};

let completedCount = 0;
let totalCount = 0;

Object.entries(progress.phases).forEach(([phase, info]) => {
  const icon = statusIcons[info.status] || '❓';
  const name = phaseNames[phase] || phase;

  console.log(`${icon} ${phase.toUpperCase()}: ${name}`);

  if (info.status === 'completed') {
    completedCount++;
    if (info.artifacts) {
      console.log(`   📁 产物: ${info.artifacts.length}个文件`);
    }
    if (info.duration) {
      console.log(`   ⏱️ 耗时: ${info.duration}秒`);
    }
  } else if (info.status === 'in_progress') {
    if (info.checkpoints) {
      console.log(`   📍 检查点: ${info.checkpoints.join(', ')}`);
    }
    if (info.pendingSteps) {
      console.log(`   ⏳ 待完成: ${info.pendingSteps.join(', ')}`);
    }
  } else if (info.status === 'failed') {
    console.log(`   ❌ 错误: ${info.error || '未知错误'}`);
  }

  totalCount++;
  console.log('');
});

// 显示进度条
const progressPercent = Math.round((completedCount / totalCount) * 100);
const progressBar = '█'.repeat(Math.floor(progressPercent / 5)) + '░'.repeat(20 - Math.floor(progressPercent / 5));

console.log('📊 总体进度:');
console.log(`[${progressBar}] ${progressPercent}% (${completedCount}/${totalCount})`);
console.log('');

// 显示恢复信息
if (progress.recovery && progress.recovery.canRecover) {
  console.log('♻️  恢复信息:');
  console.log(`   恢复点: ${progress.recovery.recoveryPoint}`);
  console.log(`   使用 npm run workflow:resume ${componentName} 继续执行`);
  console.log('');
}

// 检查产物完整性
console.log('📦 产物状态:');

const checkArtifact = (filePath) => {
  const fullPath = `./${componentName}/${filePath}`;
  if (fs.existsSync(fullPath)) {
    const stats = fs.statSync(fullPath);
    return `✅ ${(stats.size / 1024).toFixed(2)}KB`;
  }
  return '❌ 缺失';
};

const keyArtifacts = [
  'figma/figma.min.yaml',
  'figma/tokens.json',
  'figma/summary.md'
];

keyArtifacts.forEach(artifact => {
  console.log(`   ${artifact}: ${checkArtifact(artifact)}`);
});

console.log('\n---');
console.log('💡 提示:');
console.log('  继续执行: npm run workflow:resume', componentName);
console.log('  验证产物: npm run artifacts:validate', componentName);
console.log('  清理重启: npm run workflow:clean', componentName);

process.exit(0);